-- +----------------------+
-- | A editor named hexa. |
-- +----------------------+

local terminal = require "terminal"
local key      = require "key"
local screen   = require "screen"
local text     = require "text"

local hexa_term   = terminal:new{}
local hexa_key    = key:new{}
local hexa_screen = screen:new(hexa_term, {})
local hexa_text   = text:new{}

hexa_term:set_raw_mode()
hexa_screen:clear_screen()
hexa_screen:move_cursor_to(1, 1)
hexa_screen:exec_ansi()

local function exit_hexa(s, t)
    s:clear_screen()
    s:move_cursor_to(1, 1)
    s:exec_ansi()
    t:restore_normal_mode()
end

local function main()
    if arg[1] ~= nil then
        hexa_text:load(arg[1])
    end

    hexa_screen:flush(hexa_text)

    while true do
        hexa_key:read_byte()
        hexa_key:process(hexa_screen, hexa_text)
        local is_exit = hexa_screen:flush(hexa_text)
        if is_exit == 1 then
            exit_hexa(hexa_screen, hexa_term)
            break
        end
    end
end

main()